package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.goods.TbGoods;
import com.dongdongshop.pojo.goods_desc.TbGoodsDesc;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.pojo.itemCat.TbItemCat;
import com.dongdongshop.pojo.seller.TbSeller;
import com.dongdongshop.service.goods.GoodsService;
import com.dongdongshop.service.goods_jpa.GoodsJpaService;
import com.dongdongshop.service.itemCat.ItemCatService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("goods")
public class GoodsController {
    @Reference
    private GoodsService goodsService;
    private final Logger logger = LoggerFactory.getLogger(GoodsController.class);
    @Reference
    private ItemCatService itemCatService;
    @Reference
    private GoodsJpaService goodsJpaService;
    //跳转页面
    @RequestMapping("toInsertGoods")
    public String toInsertGoods(){
        return "admin/goods_edit";
    }
    //添加商品
    @RequestMapping("insertGoods")
    @ResponseBody
    public Result insertGoods(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc,String products){
        try {
            List<TbItem> tbItems = JSON.parseArray(products, TbItem.class);
            TbSeller tbSeller = (TbSeller) SecurityUtils.getSubject().getPrincipal();
            tbGoods.setSellerId(tbSeller.getSellerId());
           /* int i = goodsService.insertGoods(tbGoods,tbGoodsDesc,tbItems,tbSeller);*/
            goodsJpaService.insertGoods(tbGoods,tbGoodsDesc,tbItems,tbSeller);
            return Result.ok();
        }catch (Exception e){
            logger.error("添加商品失败",e);
            return Result.fail();
        }
    }
    @RequestMapping("toGoodsShow")
    public String toGoodsShow(){
        return "admin/goods";
    }
    @RequestMapping("listGoodsBySellerId")
    @ResponseBody
    public Result listGoodsBySellerId(){
        TbSeller tbSeller = (TbSeller) SecurityUtils.getSubject().getPrincipal();
        List<TbGoods> tbGoodsList = goodsService.listGoodsBySellerId(tbSeller);
        for (TbGoods tbGoods : tbGoodsList) {
            System.out.println(tbGoods);
            List<TbItemCat> list = itemCatService.listCategory(tbGoods.getCategory3Id());
            tbGoods.setItemCatList(list);
        }
        return Result.ok().setData(tbGoodsList);
    }
    @RequestMapping("updateAudit")
    @ResponseBody
    public Result updateAudit(@RequestParam("ids[]")Long[] ids){
        /*int i = goodsService.updateAudit(ids);*/
        goodsJpaService.updateAudit(ids);
        return Result.ok();
    }
}
